package com.yanqu.road.utils;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 固定长度List
 * 如果List里面的元素个数大于了缓存最大容量，则删除链表的顶端元素
 */
public class FixSizeLinkedList<T> extends LinkedList<T> {
	private static final long serialVersionUID = 3292612616231532364L;
	// 定义缓存的容量
	private int capacity;

	public int getCapacity() {
		return capacity;
	}

	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}

	public FixSizeLinkedList(int capacity) {
		super();
		this.capacity = capacity;
	}

	@Override
	public boolean add(T e) {
		// 超过长度，移除最后一个
		if (size() + 1 > capacity) {
			super.removeFirst();
		}
		return super.add(e);
	}

	/**
	 * 获取分页数据
	 *
	 * @param pageNumber 页码
	 * @param pageSize   每页大小
	 * @return 分页数据
	 */
	public List<T> getPage(int pageNumber, int pageSize) {
		if (pageNumber < 1 || pageSize <= 0) {
			return new ArrayList<>();
		}
		int startIndex = (pageNumber - 1) * pageSize;
		int endIndex = Math.min(startIndex + pageSize, size());
		if (startIndex >= size()) {
			return new ArrayList<>(); // 请求的页码超出了范围，返回空列表
		}
		return new ArrayList<>(this.subList(startIndex, endIndex));
	}

	public static void main(String[] args) {
		FixSizeLinkedList<String> list = new FixSizeLinkedList<>(3);
		list.add("1234");
		list.add("234");
		list.add("34");
		list.add("4");
		System.out.println(JSON.toJSONString(list));
	}
}